// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
import Keycloak, { KeycloakOnLoad } from 'keycloak-js';
import { cacheUtils } from '@/constants/util/cache-utils';

export default () => {
  const config = {
    KC_ONLOAD: 'login-required',
    KC_CONFIG: {
      clientId: 'pf',
      realm: 'test',
      url: 'http://82.156.17.159:8080/auth'
    }
  } as { KC_ONLOAD: KeycloakOnLoad | undefined; KC_CONFIG: Keycloak.KeycloakConfig | string };
  const keycloak = Keycloak(config.KC_CONFIG);
  /*
   * checkLoginIframeInterval: 5 (无效)
   * */
  const kcPromise: Promise<boolean> = keycloak
    .init({ onLoad: config.KC_ONLOAD })
    .then((authenticated: boolean) => {
      if (!authenticated) {
        throw new Error('keycloak authenticated failed : ' + authenticated);
      } else {
        console.log(keycloak.token);
        cacheUtils.set('PF_access_token', keycloak.token);
        return true;
      }
    })
    .catch(() => {
      throw new Error('keycloak init err');
    });
  keycloak.onTokenExpired = () => {
    console.log('refresh token....start........');
    keycloak.updateToken(5).then((res: boolean) => {
      console.log('refresh token....end........', res);
    });
  };
  return kcPromise;
};
